import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  NavBar,
  Tabs,
  Grid,
  Image,
  Card,
  Toast,
  Empty,
  DotLoading
} from 'antd-mobile';
import { getProductPlaceholder } from '../../utils/imageUtils';
import './Category.css';
import { useRequest } from 'ahooks';
import { getCategories, getProductByCategory } from '../../api/store';


// 分类页面
const Category = () => {
  const navigate = useNavigate();
  const { categoryId } = useParams();
  const [activeKey, setActiveKey] = useState(categoryId || '1');
  const [categories, setCategories] = useState([]);
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);

  const { runAsync: getcategoriesDataRun } = useRequest(getCategories, { manual: true });
  const { runAsync: getProductsByCategoryRun } = useRequest(getProductByCategory, { manual: true });
  const fetchCateData = async () => {
    console.log(categoryId);
    setLoading(true);
    // 模拟获取分类数据
    const categoriesData = await getcategoriesDataRun({ params: { id: 1 } });
    setCategories(categoriesData);
    console.log('获取分类数据:', categoriesData);
    // 设置默认选中的分类
    setActiveKey(categoryId);
    setLoading(false);
  }

  const fetchProData = async () => {
    if (!activeKey) return;
    setLoading(true);
    console.log('正在获取分类商品，分类ID:', activeKey);
    try {
      const productsData = await getProductsByCategoryRun({ params: { id: activeKey } });
      console.log('获取到的商品数据:', productsData);
      setProducts(productsData);
    } catch (error) {
      console.error('获取分类商品失败:', error);
      Toast.show({
        icon: 'fail',
        content: '获取商品数据失败',
      });
    }
    setLoading(false);
  }


  // 获取分类数据
  useEffect(() => {
    fetchCateData();
  }, [categoryId]);

  // 根据分类获取商品数据
  useEffect(() => {
    fetchProData();
  }, [activeKey]);

  // 获取分类名称
  const getCategoryName = (id) => {
    const category = categories.find(c => c.id === id);
    return category ? category.name : '';
  };

  // 处理分类切换
  const handleTabChange = (key) => {
    setActiveKey(key);
    navigate(`/category/${key}`);
  };

  // 处理跳转到商品详情
  const handleProductClick = (product) => {
    navigate(`/product/${product.id}`);
  };

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  // 渲染商品列表
  const renderProducts = () => {
    if (loading) {
      return (
        <div className="loading-container">
          <DotLoading color='primary' />
          <span className="loading-text">加载中</span>
        </div>
      );
    }

    if (products.length === 0) {
      return <Empty description="暂无商品" />;
    }

    return (
      <Grid columns={2} gap={10}>
        {products.map(product => (
          <Grid.Item key={product.id}>
            <Card
              className="category-product-card"
              onClick={() => handleProductClick(product)}
            >
              <Image src={product.images?.[0] || getProductPlaceholder(product.name)} fit='cover' />
              <div className="product-info">
                <div className="product-name">{product.name}</div>
                <div className="product-price">
                  <span className="price">¥{product.price.toFixed(2)}</span>
                  {product.originalPrice && (
                    <span className="original-price">¥{product.originalPrice.toFixed(2)}</span>
                  )}
                </div>
                <div className="product-sales">已售 {product.sales}</div>
              </div>
            </Card>
          </Grid.Item>
        ))}
      </Grid>
    );
  };

  return (
    <div className="category-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>商品分类</NavBar>

      {/* 分类选项卡 */}
      <Tabs
        activeKey={activeKey}
        onChange={handleTabChange}
        className="category-tabs"
      >
        {categories.map(category => (
          <Tabs.Tab key={category.id.toString()} title={category.name} />
        ))}
      </Tabs>

      {/* 商品列表 */}
      <div className="category-products">
        {renderProducts()}
      </div>
    </div>
  );
};

export default Category; 